package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

func requestVote() bool {
	time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
	return rand.Intn(10)%2 == 0
}

// 基于channel
func ch() {
	c := make(chan bool)
	voteNum := 0
	for i := 0; i < 10; i++ {
		go func() {
			c <- requestVote()
		}()
	}

	for i := 0; i < 10; i++ {
		v := <-c
		if v {
			voteNum = voteNum + 1
		}

	}
	if voteNum >= 5 {
		println("received 5+ votes!")
	} else {
		println("lost")
	}
}

// 基于lock
func con() {
	var mu sync.Mutex

	cond := sync.NewCond(&mu)
	finish := 0
	voteNum := 0

	for i := 0; i < 10; i++ {
		go func() {
			mu.Lock()
			if requestVote() {
				voteNum = voteNum + 1

			}

			finish = finish + 1
			cond.Broadcast()
			mu.Unlock()
		}()
	}

	cond.L.Lock()

	for finish != 10 && voteNum < 5 {
		cond.Wait()
	}
	if voteNum >= 5 {
		fmt.Println("vote succeed ")

	} else {
		fmt.Println("vote fail")
	}

	cond.L.Unlock()
}

func main() {
	// ch()
	a := make([]int, 0)
	fmt.Println(a[100])
}
